package cn.uexpo.lhz.controller.app;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.ServletOutputStream;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.uexpo.lhz.biz.CameranotiyBiz;
import cn.uexpo.lhz.biz.CamerastatusBiz;
import cn.uexpo.lhz.common.oldBase.BaseController;
import cn.uexpo.lhz.common.oldUtils.StringDate;
import cn.uexpo.lhz.core.http.HttpResult;
import cn.uexpo.lhz.domain.Cameranotiy;
import cn.uexpo.lhz.domain.CameranotiyExample;
import cn.uexpo.lhz.domain.Camerastatus;
import sun.misc.BASE64Decoder;

/**
 * 数点人数
 *
 * @author ldjadmin
 */
@RestController
@RequestMapping("/app/camera")
public class CameranotiyApp extends BaseController<Cameranotiy> {

    @Autowired
    private CameranotiyBiz cameranotiyBiz;
    @Autowired
    private CamerastatusBiz camerastatusBiz;


    /**
     * 上报摄像头数据
     *
     * @return
     * @throws Exception
     */
    @SuppressWarnings("restriction")
    @RequestMapping(value = "/transmitNotify", method = {RequestMethod.GET, RequestMethod.POST})
    public HttpResult transmitNotify() throws Exception {
        log.info("------------transmitNotify-----------------");
        String cameraname = request.getParameter("cameraname");//摄像头名称
        String eqpname = request.getParameter("eqpname");//设备名称
        String eqptype = request.getParameter("eqptype");//设备类型
        String address = request.getParameter("address");//安装地址
        String telephonetag = request.getParameter("telephonetag");//手机标识
        String cometotal = request.getParameter("cometotal");//当前入场总人数
        String outtotal = request.getParameter("outtotal");//当前出场总人数
        String ipaddress = request.getParameter("ipaddress");//IP地址，可以为空
        String reportTime = request.getParameter("reporttime");//上报时间：时间戳
        String base64String = request.getParameter("base64String");//图片
        String equipmentNumber = request.getParameter("equipmentNumber");//设备序列号
        long longTime = Long.parseLong(reportTime);
        Date time = StringDate.getDateTime1(StringDate.timeStamp2Date(longTime));

        Cameranotiy record = new Cameranotiy()
                .setExtstr1(cameraname)//摄像头名称
                .setEqpname(eqpname)
                .setEqptype(eqptype)
                .setAddress(address)
                .setTelephonetag(telephonetag)
                .setCometotal(Integer.parseInt(cometotal))
                .setOuttotal(Integer.parseInt(outtotal))
                .setIpaddress(ipaddress)
                .setCreatetime(StringDate.getNow()) //插入当前记录时间
                .setExttime1(time);//摄像头上报数据时间

        if (StringUtils.isNotBlank(base64String)) {
            base64String = base64String.replace(" ", "+");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] img1 = decoder.decodeBuffer(base64String);
            record.setExtimg1(img1);
        }
        record.setExtstr2(equipmentNumber);

        Calendar cal = Calendar.getInstance();
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String extstr3 = sdf.format(time);
        String extstr4 = hour + "";
        record.setExtstr3(extstr3);
        record.setExtstr4(extstr4);

        int no = cameranotiyBiz.insert(record);
//		record.setExtimg1(img1);
//		cameranotiyBiz.updateByPrimaryKeyWithBLOBs(record);
        if (no == 1) {
            return HttpResult.ok("数据上传成功");
        } else {
            return HttpResult.error("数据上传失败");
        }

    }


    /**
     * 上报摄像头状态
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/transmitStatus", method = {RequestMethod.GET, RequestMethod.POST})
    public HttpResult transmitStatus() throws Exception {
        log.info("------------transmitNotify-----------------");
        String cameraname = request.getParameter("cameraname");//摄像头名称
        String eqpname = request.getParameter("eqpname");//设备名称
        String status = request.getParameter("status");//摄像头链接状态：0已关闭1已链接
        String reportTime = request.getParameter("reporttime");//上报时间：时间戳
        String equipmentNumber = request.getParameter("equipmentNumber");//设备序列号
        long longTime = Long.parseLong(reportTime);
        Date time = StringDate.getDateTime1(StringDate.timeStamp2Date(longTime));
        Camerastatus record = new Camerastatus();
        record.setExtstr1(cameraname);//摄像头名称
        record.setEqpname(eqpname);
        record.setStatus(status);
        record.setCreatetime(StringDate.getNow());//插入当前记录时间
        record.setSendtime(time);//摄像头上报数据时间
        record.setExtstr2(equipmentNumber);
        int no = camerastatusBiz.insert(record);
        if (no == 1) {
            return HttpResult.ok("摄像头状态上传成功");
        } else {
            return HttpResult.error("摄像头状态上传失败");
        }

    }


    /**
     * 查询人数
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/miaohuiStatistics", method = {RequestMethod.GET, RequestMethod.POST})
    public Map<String, Object> miaohuiStatistics() throws Exception {
        log.info("------------miaohuiStatistics-----------------");
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = "未查到数据";//消息提示
        String code = "400";//返回码
        String entryName = "";//项目名称
        int getInto = 0;//进入人数
        int getOut = 0;//出去人数
        int id = 0;//最新记录id


        String reprotTime = "";//摄像头传过来数据的时间
        String createTime = "";//后台接收数据的时间
        CameranotiyExample Example = new CameranotiyExample();
        CameranotiyExample.Criteria citeria = Example.createCriteria();
        entryName = dictionaryUtil.getItemValueUsable("statistics", "srs_install_address1");//安装地址名称（默认：马术赛3号口）
        citeria.andAddressEqualTo(entryName);//配置未“庙会”
        String orderBy = " extTime1 ";//按照摄像头最新数据 时间降序
        String sort = " desc ";//默认按照时间降序
        Example.setOrderByClause(orderBy + sort);
        List<Cameranotiy> cameranotiys = cameranotiyBiz.selectByExample(Example);
        if (cameranotiys != null && cameranotiys.size() > 0) {
            Cameranotiy record = cameranotiys.get(0);
            getInto = record.getCometotal();
            getOut = record.getOuttotal();
            msg = "已查到数据";
            code = "200";
            id = record.getId();
            reprotTime = StringDate.DateToString(record.getExttime1());
            createTime = StringDate.DateToString(record.getCreatetime());
        }

        String frequency = dictionaryUtil.getItemValueUsable("statistics", "srs_xcx_time_frequency");//小程序刷新频率(默认：30000)
        map.put("msg", msg);
        map.put("code", code);
        map.put("id", id);
        map.put("reprotTime", reprotTime);
        map.put("createTime", createTime);
        map.put("frequency", frequency);

        map.put("entryName", entryName);
        map.put("getInto", getInto);
        map.put("getOut", getOut);
        return map;
    }

    /**
     * 图片展示
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/showImg", method = {RequestMethod.GET, RequestMethod.POST})
    public Map<String, Object> showImg() throws Exception {
        log.info("------------miaohuiStatistics-----------------");
        Map<String, Object> map = new HashMap<String, Object>();
        String lastCameraId = request.getParameter("lastCameraId");
        Cameranotiy record = cameranotiyBiz.selectByPrimaryKey(Integer.parseInt(lastCameraId));
        ServletOutputStream out = null;
        response.setContentType("image/*");
        if (record != null) {
            byte[] image = record.getExtimg1();
            if (image != null && image.length > 0) {
                try {
                    out = response.getOutputStream();
                    out.write(image);
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }

}
